package com.araaya.eslimsmobile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.araaya.eslimsmobile.R;
import com.araaya.eslimsmobile.adapter.PointListAdapter;
import com.araaya.eslimsmobile.db.DatabaseFunction;
import com.araaya.eslimsmobile.db.GPSLand;
import com.araaya.eslimsmobile.gps.ListenLocation;
import com.araaya.eslimsmobile.gps.MobileKmlWriter;
import com.araaya.eslimsmobile.util.ElandConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class NewLand extends Activity {

	// private ListView pointListView;
	private EditText txtLandName;

	// public static ArrayList<HashMap<String, String>> pointList;
	// private ListAdapter pointAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_land);

		// pointList = new ArrayList<HashMap<String, String>>();

		// Land Name Text Field
		txtLandName = (EditText) findViewById(R.id.txtLandName);

		// point List
		// pointListView = (ListView) findViewById(R.id.pointList);

		// create the adapter
		/*
		 * if (KmlHome.pointList != null) { pointAdapter = new
		 * PointListAdapter(NewLand.this, KmlHome.pointList,
		 * R.layout.point_list_view, new String[] { "lat" }, new int[] {
		 * R.id.item_title });
		 * 
		 * pointListView.setAdapter(pointAdapter);
		 * 
		 * } pointListView.setVisibility(View.GONE);
		 */

		final Button btnAddPoint = (Button) findViewById(R.id.btnAddPoint);
		final Button btnNewLandSave = (Button) findViewById(R.id.btnNewLandSave);
		final Button btnCreateKml = (Button) findViewById(R.id.btnCreateKml);
		final Button btnShowMap = (Button) findViewById(R.id.btnShowMap);
		final Button btnViewArea = (Button) findViewById(R.id.btnViewArea);

		// Add point Button -- Add a new GPS point to kml
		btnAddPoint.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				NewLandMapAlert();

			}
		});

		// Save Land Button -- save the points tn db
		btnNewLandSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				String landName = txtLandName.getText().toString();
				if (landName.length() > 0) {
					if (KmlHome.pointList.size() > 2) {
						if (saveLand(landName)) {
							Toast.makeText(NewLand.this,
									ElandConstant.SAVE_LAND_SUCCESS_STR,
									Toast.LENGTH_LONG).show();
							finish();
						} else {
							Toast.makeText(NewLand.this,
									ElandConstant.SAVE_LAND_FAILD_STR,
									Toast.LENGTH_LONG).show();
						}

					} else {
						Toast.makeText(NewLand.this,
								ElandConstant.MINIMUN_POINT_STR,
								Toast.LENGTH_LONG).show();
					}

				} else {
					Toast.makeText(NewLand.this, ElandConstant.NO_FILENAME_STR,
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// Create Kml File Button -- create the kml file
		btnCreateKml.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String landName = txtLandName.getText().toString();
				if (landName.length() > 0) {
					if (KmlHome.pointList.size() > 2) {

						if (saveLand(landName)) {
							Toast.makeText(NewLand.this,
									ElandConstant.SAVE_LAND_SUCCESS_STR,
									Toast.LENGTH_LONG).show();

							if (createFile(landName, KmlHome.pointList)) {
								Toast.makeText(NewLand.this,
										ElandConstant.CTRATE_KML_SUCCESS_STR,
										Toast.LENGTH_LONG).show();
								finish();
							} else {
								Toast.makeText(NewLand.this,
										ElandConstant.SAVE_LAND_FAILD_STR,
										Toast.LENGTH_LONG).show();
							}

						} else {
							Toast.makeText(NewLand.this,
									ElandConstant.SAVE_LAND_FAILD_STR,
									Toast.LENGTH_LONG).show();
						}

					} else {
						Toast.makeText(NewLand.this,
								ElandConstant.MINIMUN_POINT_STR,
								Toast.LENGTH_LONG).show();
					}

				} else {
					Toast.makeText(NewLand.this, ElandConstant.NO_FILENAME_STR,
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// Show Map Button -- Show the current Map
		btnShowMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (KmlHome.pointList.size() > 0) {
					Intent i = new Intent(getApplicationContext(),
							MyMapViewer.class);
					i.putExtra("coordinate",
							getAllCoordinates(KmlHome.pointList));
					startActivity(i);

					/*
					 * Intent i = new Intent(getBaseContext(), WebHome.class);
					 * startActivity(i);
					 */

					/*
					 * String coordinates=getAllCoordinates(KmlHome.pointList);
					 * 
					 * MobileKmlWriter kmlWriter = new MobileKmlWriter();
					 * kmlWriter.getMiddlePoint(coordinates); long
					 * refNo=kmlWriter.getReferenceNo();
					 */

				} else {
					Toast.makeText(NewLand.this,
							ElandConstant.SHOW_MAP_NO_POINT_STR,
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// Calculate Area Button -- Calculate the Map area
		btnViewArea.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (KmlHome.pointList.size() > 0) {
					String coordinates = getAllCoordinates(KmlHome.pointList);

					MobileKmlWriter kmlWriter = new MobileKmlWriter();
					String middlePoint = kmlWriter.getMiddlePoint(coordinates);
					long refNo = kmlWriter.getReferenceNo();

					Intent i = new Intent(getBaseContext(), WebHome.class);
					i.putExtra("coordinate", coordinates);
					i.putExtra("middlePoint", middlePoint);
					i.putExtra("refNo", refNo);
					startActivity(i);
				} else {
					Toast.makeText(NewLand.this,
							ElandConstant.SHOW_MAP_NO_POINT_STR,
							Toast.LENGTH_LONG).show();
				}

			}
		});

		// click the Point List view
		/*
		 * pointListView.setTextFilterEnabled(true);
		 * pointListView.setOnItemClickListener(new OnItemClickListener() {
		 * public void onItemClick(AdapterView<?> parent, View view, int
		 * position, long id) {
		 * 
		 * @SuppressWarnings("unchecked") HashMap<String, String> o =
		 * (HashMap<String, String>) pointListView .getItemAtPosition(position);
		 * pointListAlert(position);
		 * 
		 * } });
		 */

	}

	@Override
	protected void onResume() {
		super.onResume();
		// ((BaseAdapter) pointAdapter).notifyDataSetChanged();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			backMapAlert();
			return true;

		}
		return super.onKeyDown(keyCode, event);
	}

	// GPS Location
	public boolean getLocation() {
		LocationManager locationManager = null;
		LocationListener locationListener;
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			locationListener = new ListenLocation();
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			return true;
		} else {
			return false;
		}

	}

	// remove point in Point list
	/*
	 * private void removePointByPosition(int pos) {
	 * KmlHome.pointList.remove(pos); ((BaseAdapter)
	 * pointAdapter).notifyDataSetChanged(); }
	 */

	/*
	 * private void pointListAlert(final int pos) { AlertDialog.Builder alt_bld
	 * = new AlertDialog.Builder(this); alt_bld.setMessage("")
	 * .setCancelable(false) .setPositiveButton("Delete Point", new
	 * DialogInterface.OnClickListener() { public void onClick(DialogInterface
	 * dialog, int id) {
	 * 
	 * removePointByPosition(pos); return;
	 * 
	 * } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	 * public void onClick(DialogInterface dialog, int id) {
	 * 
	 * dialog.cancel(); return;
	 * 
	 * } });
	 * 
	 * AlertDialog alert = alt_bld.create(); // Title for AlertDialog
	 * alert.setTitle("eLand Mobile"); // Icon for AlertDialog
	 * alert.setIcon(R.drawable.point); alert.show();
	 * 
	 * }
	 */
	// save the kml file
	public boolean createFile(String landName,
			ArrayList<HashMap<String, String>> points) {

		// Create Folder
		File folder = new File(Environment.getExternalStorageDirectory()
				.toString() + "/eLand/kml");
		folder.mkdirs();

		// Save the path as a string value
		String extStorageDirectory = folder.toString();
		String oldfilename = landName + ".kml";
		String filename = oldfilename.replace("/", "_");
		Log.d("AAAA", oldfilename);
		Log.d("BBBB", filename);
		// Create New file and name it
		File file = new File(extStorageDirectory, filename);

		FileOutputStream fos;
		// byte[] data = new String("Kusal").getBytes();

		MobileKmlWriter kmlWriter = new MobileKmlWriter();
		String kmlString = kmlWriter.writeKmlFile(file, points);
		if (kmlString != null) {
			byte[] data = kmlString.getBytes();

			try {
				fos = new FileOutputStream(file);
				fos.write(data);
				fos.flush();
				fos.close();
				return true;
			} catch (FileNotFoundException e) {
				Log.d("FileNotFoundException", e.getMessage());
				return false;
				// handle exception
			} catch (IOException e) {
				Log.d("IOException", e.getMessage());
				return false;
			}
		} else {
			return false;
		}

	}

	private boolean saveLand(String landName) {
		try {
			DatabaseFunction databaseFunction = new DatabaseFunction(
					NewLand.this);

			GPSLand land = new GPSLand();
			land.setLandName(landName);
			land.setCoordinates(getAllCoordinates(KmlHome.pointList));
			long l = databaseFunction.addGPSLand(land);
			if (l != -1) {
				// pointList.clear();
				Log.d("save row", "" + l);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			Log.d("NewLand Exception", e.getMessage());
			return false;
		}

	}

	private String getAllCoordinates(ArrayList<HashMap<String, String>> points) {
		String cordinate = "";
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < points.size(); i++) {
			String lat, lon, alt = "";
			map = points.get(i);
			lon = map.get("lon");
			lat = map.get("lat");
			alt = map.get("alt");

			cordinate = cordinate + lon + "," + lat + "," + alt + " ";

		}

		return cordinate;
	}

	// New Land Alert
	public void NewLandMapAlert() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(ElandConstant.NEW_MAP_ALERT)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								KmlHome.pointList.clear();
								Intent i = new Intent(getApplicationContext(),
										LocationMapper.class);
								startActivity(i);
								finish();

							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'NO' Button
						dialog.cancel();
					}
				});
		AlertDialog alert = alt_bld.create();
		alert.show();
	}

	// Message Alert
	public void displayAlert(String message, String title, String btnTxt,
			Integer image) {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(btnTxt,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {

								dialog.cancel();
								return;

							}
						});

		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(title);
		// Icon for AlertDialog
		alert.setIcon(image);
		alert.show();
	}

	// exit from kml map Alert
	public void backMapAlert() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(ElandConstant.SAVE_LAND_CONFIRM_STR)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'NO' Button
						KmlHome.pointList.clear();
						finish();
					}
				});
		AlertDialog alert = alt_bld.create();
		alert.show();
	}

}
